package com.sinaweibo.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.sinaweibo.po.WeiboImagePO;

/**
 * @author Jeson
 * @blog:http://www.ij2ee.com
 * @date:2011-4-16 上午11:41:13
 * @version :1.0
 * 
 */
public class HttpUtil {
	public static String charCode = "utf-8";
	public static DefaultHttpClient client = null;

	/**
	 * 使用get方法提交
	 * 
	 * @param client
	 *            HttpClient对象
	 * @param url
	 *            提交地址
	 * @param referer
	 *            Referer信息
	 * @return 请求后返回的网页流
	 * @throws ContactListImporterException
	 * @throws URISyntaxException
	 * @throws InterruptedException
	 * @throws HttpException
	 * @throws IOException
	 */

	public static  String doGetString(String url, String referer) throws Exception {
		getHttpClient().getConnectionManager().closeIdleConnections(0L,
				TimeUnit.MILLISECONDS);
		HttpGet get = new HttpGet(url);
		get.setHeader("Content-Type", "text/html; charset=" + charCode);
		setHeaders(get, referer);
		// client.getParams().setParameter("http.socket.timeout", 60000);
		return EntityUtils.toString(client.execute(get).getEntity(), "UTF-8");
	}

	/**
	 * 使用post方法提交
	 * 
	 * @param client
	 *            HttpClient对象
	 * @param url
	 *            提交地址
	 * @param data
	 *            要提交到服务器的参数
	 * @param referer
	 *            头部Referer信息
	 * @return 请求后返回的网页流
	 * @throws ContactListImporterException
	 * @throws HttpException
	 * @throws IOException
	 * @throws InterruptedException
	 * @throws URISyntaxException
	 */
	public static  InputStream doPost(HttpClient client, String url,
			NameValuePair data[], String referer) throws HttpException,
			IOException, InterruptedException, URISyntaxException {
		client.getConnectionManager().closeIdleConnections(0L,
				TimeUnit.MILLISECONDS);
		if (url.indexOf("?") != -1)
			url = url + "&dd=" + System.currentTimeMillis();
		HttpPost post = new HttpPost(url);
		setHeaders(post, referer);
		// post.addHeader("Content-Type", "application/x-www-form-urlencoded");
		post.setHeader("Content-Type", "text/html; charset=" + charCode);
		List<NameValuePair> dlist = new ArrayList<NameValuePair>();
		for (NameValuePair nv : data) {
			dlist.add(nv);
		}
		post.setEntity(new UrlEncodedFormEntity(dlist));
		HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
		HttpProtocolParams.setUseExpectContinue(post.getParams(), false);
		String response = EntityUtils.toString(
				client.execute(post).getEntity(), "UTF-8");
		return null;
	}

	public static  String doPostString(String url, NameValuePair data[],
			String referer) throws Exception {

		/*
		 * getHttpClient().getConnectionManager().closeIdleConnections(0L,
		 * TimeUnit.MILLISECONDS);
		 */
		/*
		 * if (url.indexOf("?") != -1) url = url + "&dd=" +
		 * System.currentTimeMillis();
		 */
		HttpPost post = new HttpPost(url);
		// setHeaders(post, referer);
		// post.addHeader("refer", referer);
		// post.addHeader("Host","weibo.gb246.com");
		// post.setHeader("Content-Type", "text/html; charset="+charCode);
		List<NameValuePair> dlist = new ArrayList<NameValuePair>();
		for (NameValuePair nv : data) {
			dlist.add(nv);
		}
		post.setEntity(new UrlEncodedFormEntity(dlist,HTTP.UTF_8));
		// HttpProtocolParams.setUseExpectContinue(getHttpClient().getParams(),
		// false);
		// HttpProtocolParams.setUseExpectContinue(post.getParams(), false);

		return EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
	}

	private static String regex = "window.parent.imageUploadifyComplete\\('([^']+)', '([^']+)', '([^']+)'\\);";

	/**
	 * httpclient 上传图片
	 * 
	 * @param data
	 *            其他字符串行的参数
	 * @param uploadUrl
	 *            要上传的请求路径
	 * @return
	 * @throws URISyntaxException
	 * @throws HttpException
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static WeiboImagePO uploadFile(Map<String, Object> data, String uploadUrl)
			throws URISyntaxException, HttpException, IOException,
			InterruptedException {
		HttpPost post = new HttpPost(uploadUrl);
		MultipartEntity multipartEntity = new MultipartEntity(
				HttpMultipartMode.BROWSER_COMPATIBLE);
		// multipartEntity.addPart( "topic", new FileBody(file));

		// 设置其他参数
		for (Map.Entry<String, Object> entry : data.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();
			if (value == null) {
				throw new NullPointerException("要传到服务器的对象不能为空");
			}
			if (value instanceof File) {
				multipartEntity.addPart(key, new FileBody((File) value));
			} else if (value instanceof InputStream) {
				multipartEntity.addPart(key, new InputStreamBody(
						(InputStream) value, "额  自己想办法弄文件名吧 !可以试试UUID"));
			} else if (value instanceof byte[]) {
				multipartEntity.addPart(key, new ByteArrayBody((byte[]) value,
						"额  自己想办法弄文件名吧!可以试试UUID"));
			} else {
				multipartEntity.addPart(key, new StringBody(value.toString()));
			}
		}
		post.setEntity(multipartEntity);
		HttpResponse response = client.execute(post);
		InputStream content = response.getEntity().getContent();
		String imgCon = readInputStream(content, charCode);
		if(imgCon.indexOf("pic is empty")!=-1){
			log.error("pic  is null with path:"+uploadUrl);
			return null;
		}
		if(imgCon.indexOf("Error report")!=-1){
			log.error("pic server has exception  is null with path:"+uploadUrl);
			return null;
		}
		//log.info(imgCon);
		//System.out.println(imgCon);
		int[] ind = { 1, 2, 3 };
		List<String> list = StringUtil.getStringsByRegex(regex, ind, imgCon);
		WeiboImagePO po = new WeiboImagePO();
		po.setImageId(list.get(0));
		po.setImagePath(list.get(1));
		return po;
	}

	/**
	 * 读取流并拼接转换成字符串
	 * 
	 * @param is
	 *            流
	 * @param encode
	 *            字符集编码 null的时候为gb2312
	 * @return 转换后的字符串
	 * @throws IOException
	 */
	public static  String readInputStream(InputStream is, String encode)
			throws IOException {
		if (encode == null) {
			encode = "gb2312";
		}
		BufferedReader in = new BufferedReader(
				new InputStreamReader(is, encode));
		StringBuffer buffer = new StringBuffer();
		String line;

		while ((line = in.readLine()) != null) {
			buffer.append(line);
		}
		is.close();
		return buffer.toString();
	}

	public static  void setHeaders(HttpRequest req, String referer) {
		// req.addHeader(
		// "Accept",
		// "text/xml,text/javascript,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
		// req.addHeader("Accept-Language", "en-us;q=0.7,en;q=0.3");
		// req.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
		// if (referer != null)
		// req.addHeader("Referer", referer);
	}

	public   static DefaultHttpClient getHttpClient() {
		/**
		 * 修改了单例模式 防止URL缓存
		 */
		if (client == null) {
			client = new DefaultHttpClient(new ThreadSafeClientConnManager());
			/*
			 * client.getParams().setParameter("http.protocol.cookie-policy",
			 * "compatibility");
			 */
			List<Header> headers = new ArrayList<Header>();
			client.getParams().setParameter("http.default-headers", headers);
			return client;
		} else {
			return client;
		}
	}

	public void printCookie(DefaultHttpClient client) {
		System.out.println("Initial set of cookies:");
		List<Cookie> cookies = client.getCookieStore().getCookies();
		if (cookies.isEmpty()) {
			System.out.println("None");
		} else {
			for (int i = 0; i < cookies.size(); i++) {
				System.out.println("- " + cookies.get(i).toString());
			}
		}

	}

	public static  NameValuePair[] fillParam(Map<String, String> dataMap) {
		NameValuePair data[] = new NameValuePair[dataMap.size()];
		Iterator iterator = dataMap.keySet().iterator();
		int i = 0;
		while (iterator.hasNext()) {
			String ks = iterator.next().toString();
			data[i++] = new BasicNameValuePair(ks, dataMap.get(ks));
			// System.out.println(dataMap.get(iterator.next()));
		}
		/*
		 * for(int i=0;i<dataMap.size();i++){ data[i] = new
		 * BasicNameValuePair(key[i].toString(),dataMap.get(key)); }
		 */
		return data;
	}

	public List<Node> parseList(Parser p, NodeFilter f) throws ParserException {
		NodeList nl = p.extractAllNodesThatMatch(f);
		if (nl == null || nl.size() == 0)
			return null;
		List<Node> list = new ArrayList<Node>();
		for (int i = 0; i < nl.size(); i++) {
			list.add(nl.elementAt(i));
		}
		return list;
	}
	
	public static int getHttpStatus(String urlStr) throws IOException{
		 URL url = new URL(urlStr);
         URLConnection rulConnection   = url.openConnection();
         HttpURLConnection httpUrlConnection  =  (HttpURLConnection) rulConnection;
         String code = new Integer(httpUrlConnection.getResponseCode()).toString();
         return Integer.parseInt(code);
	}
	
	public static void main(String[] args) throws IOException {
		System.out.println(getHttpStatus("http://www.qjiafang.com/"));
	}
	private static Logger log = Logger.getLogger(HttpUtil.class);
}
